/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cw.controller;

import cw.controller.exceptions.NonexistentEntityException;
import cw.controller.exceptions.PreexistingEntityException;
import cw.entity.User;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

/**
 *
 * @author VinhTC
 */
public class UserJpaController {
    
    public UserJpaController() {
        emf = Persistence.createEntityManagerFactory("CrossWordsAdminPU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {

        return emf.createEntityManager();
    }

    public void create(User user) throws PreexistingEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            em.persist(user);
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findUser(user.getUserId()) != null) {
                throw new PreexistingEntityException("User " + user + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(User user) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            user = em.merge(user);
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = user.getUserId();
                if (findUser(id) == null) {
                    throw new NonexistentEntityException("The user with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            User user;
            try {
                user = em.getReference(User.class, id);
                user.getUserId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The user with id " + id + " no longer exists.", enfe);
            }
            em.remove(user);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<User> findUserEntities() {
        return findUserEntities(true, -1, -1);
    }

    public List<User> findUserEntities(int maxResults, int firstResult) {
        return findUserEntities(false, maxResults, firstResult);
    }

    private List<User> findUserEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(User.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public User findUser(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(User.class, id);
        } finally {
            em.close();
        }
    }

    public int getUserCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<User> rt = cq.from(User.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

    /**
     * getUserByEmail
     * @param email
     * @return
     */
    public User getUserByEmail(String email) {
        try {
            Query query = getEntityManager().createNamedQuery("User.findByEmail");
            query.setParameter("email", email);
            return (User) query.getSingleResult();
        } catch (Exception ex) {
            Logger.getLogger(UserJpaController.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

    /**
     * getUserByUserNameAndPassword
     * @param username
     * @param pass
     * @return
     */
    public User getUserByUserNameAndPassword(String username, String pass) {
        try {
            Query query = getEntityManager().createNamedQuery("User.findByUserNameAndPassword");
            query.setParameter("userName", username);
            query.setParameter("password", pass);

            return (User) query.getSingleResult();
        } catch (Exception e) {
            Logger.getLogger(UserJpaController.class.getName()).log(Level.SEVERE, null, e);
            return null;
        }
    }

    /**
     * getUserByUserName
     * @param username
     * @return User
     */
    public User getUserByUserName(String username) {
        try {
            Query query = getEntityManager().createNamedQuery("User.findByUserName");
            query.setParameter("userName", username.trim());

            return (User) query.getSingleResult();
        } catch (Exception e) {
            Logger.getLogger(UserJpaController.class.getName()).log(Level.SEVERE, null, e);
            return null;
        }
    }
}
